package ext.tianma.project.processors;

import java.util.List;

import wt.fc.ObjectIdentifier;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.projmgmt.admin.Project2;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionServerHelper;
import wt.util.WTException;

import com.ptc.core.components.forms.FormResult;
import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.projectmanagement.plan.Plan;
import com.ptc.projectmanagement.plan.PlanActivity;
import com.ptc.projectmanagement.plan.Plannable;
import com.ptc.projectmanagement.plan.processors.TrackActivityWorkFormProcessor;

public class CusTrackActivityWorkFormProcessor extends TrackActivityWorkFormProcessor{

	@Override
	public FormResult doOperation( NmCommandBean nmCommandBean , List list ) throws WTException {

		return super.doOperation( nmCommandBean , list );
	}

	@Override
	public FormResult postProcess( NmCommandBean nmCommandBean , List list ) throws WTException {
		FormResult formResult = super.postProcess( nmCommandBean , list );
			
		Object object = nmCommandBean.getElementContext().getTargetOid().getRefObject();
		
		if( object != null ){			
			if( object instanceof ObjectReference ){
				ObjectReference orf = ( ObjectReference )object;
				object = orf.getObject();
			}
			
			if( object instanceof PlanActivity ){
				PlanActivity sonPlanActivity = ( PlanActivity )object;
				
				if( !sonPlanActivity.isMilestone() ){
					String sonName = sonPlanActivity.getName();
					
					//根据活动获取项目				
					Project2 sonProject = ( Project2 )sonPlanActivity.getContainer();
					//开起权限
					boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
					try{
						if( sonProject != null ){					
							//获取项目名称通过名称来判断该项目为主项目还是子项目
							String sonProjectName = sonProject.getName();
							String[] parentName = sonProjectName.split("_");
							
							if( sonName.contains( ">" ) && parentName != null && parentName.length != 1){
								PlanActivity parentPlanActivity = getPlanActivity( sonPlanActivity , sonProject );
								
								if( parentPlanActivity == null ){
									throw new WTException("此活动在主项目中没有对应活动，请找相关人士修改活动名称在进行提交");
								}
							}else if( !sonName.contains( ">" ) && parentName != null && parentName.length != 1 ){
								
								//通过活动获取汇总活动，当没有汇总活动的时候则获取到的是计划
								Plannable sonPlan = sonPlanActivity.getParentPlannable();
								
								if( sonPlan instanceof Plan ){
									
									PlanActivity parentPlanActivity = getPlanActivity( sonPlanActivity , sonProject );
									
									if( parentPlanActivity == null ){
										throw new WTException("此活动在主项目中没有对应活动，请找相关人士修改活动名称在进行提交");
									}
									
								}else{
									
									PlanActivity parentPlanActivity = getPlanActivity( (PlanActivity)sonPlan , sonProject );
									
									if( parentPlanActivity == null ){
										throw new WTException("此活动在主项目中没有对应活动，请找相关人士修改活动名称在进行提交");
									}
									
								}
							}
						}
					}finally{
						SessionServerHelper.manager.setAccessEnforced(flag);
					}					
				}
			}			
		}

		return formResult;
	}

	@Override
	public FormResult setResultNextAction( FormResult formResult , NmCommandBean nmCommandBean , List list ) throws WTException {

		return super.setResultNextAction( formResult , nmCommandBean , list );
	}
	
	/**
	 * 根据子活动和子项目来获取主项目中对应的主活动
	 * @param sonPlanActivity
	 * @param sonProject
	 * @return
	 * @throws WTException
	 */
	private PlanActivity getPlanActivity( PlanActivity sonPlanActivity , Project2 sonProject ) throws WTException{
		PlanActivity parentPlanActivity = null;
		
		if( sonPlanActivity == null || sonProject == null ){
			return parentPlanActivity;
		}
		
		String sonName = sonProject.getName();
			
		if( sonName != null && !sonName.trim().isEmpty() ){
				
			String[] strName = sonName.split("_");
				
			if( strName != null && strName.length != 1 ){
					
				String parentName = strName[0];
				System.out.println( "Debug   主项目名称："+ parentName );
				System.out.println( "Debug   主活动名称：" + sonPlanActivity.getName() );
				if( parentName != null && !parentName.trim().isEmpty() ){
						
					Project2 parentProject = getProject2ByName( parentName.trim() );
					
					System.out.println( "Debug   parentProject : " + parentProject );
					
					if( parentProject != null ){								
						//根据子活动来获取主项目中的对应活动
						parentPlanActivity = querySeekPlanActivity( sonPlanActivity , parentProject );
																						
					}							
				}
			}					
		}
		return parentPlanActivity;
	}
	
	/**
	 * 根据当前活动来获取指定项目中相同的活动
	 * @param planActivity   （指定需要查找的活动）
	 * @param parentProject2
	 * @return
	 * @throws WTException
	 */
	public static PlanActivity querySeekPlanActivity( PlanActivity planActivity , Project2 parentProject2 ) throws WTException{
		PlanActivity planAT = null;
		//根据项目获取对应的项目中所有的活动
		QueryResult qry = getPlanActivityByProject( parentProject2 );
		
		boolean isExist = false;
		
		while( qry.hasMoreElements() ){
			Object object = qry.nextElement();
			
			if( object != null && object instanceof PlanActivity ){
				planAT = ( PlanActivity )object;
				System.out.println( "Debug   planAT.getName():"+planAT.getName()+"...planActivity.getName():"+planActivity.getName() );
				if( planAT.getName().trim().equals( planActivity.getName().trim() ) ){
					isExist = true;
					break;
				}
			}
		}
		
		if( isExist == false ){
			planAT = null;
		}
		return planAT;
	}

	/**
	 * 通过名称来获取项目
	 * @param name
	 * @return
	 * @throws WTException
	 */
	public static Project2 getProject2ByName(String name) throws WTException{
		System.out.println( "Debug   name : " + name );
		Project2 project=null;
		QuerySpec qs=null;
		QueryResult qr=null;
		qs= new QuerySpec(Project2.class);
		//根据零件编号查询
		SearchCondition sc = new SearchCondition(Project2.class, Project2.NAME, SearchCondition.LIKE, name);		     
		qs.appendSearchCondition(sc);		    			
		qr= PersistenceHelper.manager.find(qs);
		if(qr.hasMoreElements()){
			project=(Project2)qr.nextElement();				
		}
		return project;
		
	}
	
	/**
     * 根据项目获取对应的项目任务
     */
    public static QueryResult getPlanActivityByProject( Project2 project) throws WTException {
		QuerySpec qs = null;
		QueryResult qr = null;
		qs = new QuerySpec(PlanActivity.class);
		ReferenceFactory rf = new ReferenceFactory();
		ObjectIdentifier objId = ObjectIdentifier.newObjectIdentifier(rf.getReferenceString(project));
		SearchCondition sc = new SearchCondition(PlanActivity.class, "containerReference.key", SearchCondition.EQUAL, objId);
		qs.appendSearchCondition(sc);
		qs.appendOrderBy(PlanActivity.class, PlanActivity.LINE_NUMBER, false);
		qr = PersistenceHelper.manager.find(qs);
		return qr;
    }
	
}
